package com.fc.advbox.common.upload;

import org.apache.commons.fileupload.FileUploadException;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.UUID;

public class DefaultFileUploadManager implements FileUploadManager {
    @Override
    public String upload(MultipartFile file) throws FileUploadException {
        try {
            // 这里只是简单例子，文件直接输出到项目路径下。
            // 实际项目中，文件需要输出到指定位置，需要在增加代码处理。
            // 还有关于文件格式限制、文件大小限制，详见：中配置。
            if (!file.isEmpty()) {
                String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
                BufferedOutputStream out = new BufferedOutputStream(
                        new FileOutputStream(new File(filename)));
                out.write(file.getBytes());
                out.flush();
                out.close();
                return filename;
            } else {
                throw new FileUploadException("File is empty");
            }
        } catch (FileNotFoundException e) {
            throw new FileUploadException("Failed to upload, file not found", e);
        } catch (IOException e) {
            throw new FileUploadException("Failed to upload, IOException", e);
        }
    }

    @Override
    public String[] batchUpload(List<MultipartFile> files) throws FileUploadException {
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        String[] paths = new String[files.size()];
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(":"));
            String filename = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            if (!file.isEmpty()) {
                try {
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(new File(filename)));
                    stream.write(bytes);
                    stream.close();
                    paths[i] = filename;
                } catch (Exception e) {
                    stream = null;
                    throw new FileUploadException("Failed to batch upload", e);
                }
            } else {
                throw new FileUploadException("File is empty");
            }
        }
        return paths;
    }
}
